package com.kzy.demoadmin.web.config;

import cn.hutool.core.util.ObjectUtil;
import com.kzy.demoadmin.web.entity.Log;
import com.kzy.demoadmin.web.entity.Result;
import com.kzy.demoadmin.web.entity.User;
import com.kzy.demoadmin.web.service.LogService;
import com.kzy.demoadmin.web.utils.JwtTokenUtils;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.time.format.DateTimeFormatter;

import java.time.LocalDateTime;

@Slf4j
@Component
@Aspect// 切面 TO了解
public class LogAspect {
    @Autowired
    private LogService logService;

    @Around("@annotation(autoLog)")//围绕
    public Object doAround(ProceedingJoinPoint joinPoint, AutoLog autoLog) throws Throwable {

        //操作内容，我们在注解里定义了value
        String name = autoLog.value();
        // 时间
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String time = now.format(formatter);
        //操作人
        String username = "";

        User user = JwtTokenUtils.getCurrentUser();

        if (ObjectUtil.isNotNull(user)) {
            username = user.getUsername();
        }

        //操作人Ip
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String ip = request.getRemoteAddr();//获取ip

        //执行接口
        Result result = (Result) joinPoint.proceed();

        //判断返回结果，如果是登录获取到data，则获取用户名
        Object data = result.getData();
        if (data instanceof User){
            User u = (User) data;
            username = u.getUsername();
        }

        //保存日志
        Log log = new Log(name, time, username, ip);
        logService.add(log);

        return result;
    }

}
